import logging
#from Errors import NotEnoughManaError
#from UserDict import UserDict

__author__ = "esoso"
__date__ = "$Jun 29, 2009 9:13:26 AM$"

log = logging.getLogger(__name__)

class ManaPool(dict):

    def __init__(self):
        self.mapping = ['U', 'G', 'R', 'B', 'W', 'C']
        self['G'] = 0
        self['R'] = 0
        self['B'] = 0
        self['W'] = 0
        self['C'] = 0
        self['U'] = 0

    def addMana(self, color, qty):
        self[color] += qty

    def pay(self, card):
        '''
        Accept dict like {'U': 3, 'C': 2}
        '''
        return self._check_colored(card) and self._check_uncolored(card)
        
    def _check_colored(self, card):
        '''
        Return true if colored part is ok to pay spell, false otherwise
        '''
        coloredMana = [col for col in card.cost.keys() if col <> 'U']
        for color in coloredMana:
            if self[color] < card.cost[color]:
                return False
            else:
                self[color] -= card.cost[color]
        return True

    def _check_uncolored(self, card):
        """Verify amount of uncolored mana"""
        total = sum([self[i] for i in self.mapping])
        uncost = card.cost['U']
        if uncost > total:
            return False
        else:
            self._subtract_mana(uncost)
            return True

    def _subtract_mana(self, cost, color_index=0):
        if not cost == 0:
            color = self[self.mapping[color_index]]
            if cost >= color:
                self[self.mapping[color_index]] = 0
                color_index += 1
                self._subtract_mana(cost - color, color_index)
            else:
                color -= cost
                
